
package com.zcp.wizard;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.view.View;
import android.widget.RemoteViews;

import java.util.Timer;
import java.util.TimerTask;

public class WidgetUtils {

    private static final int[] wgCpuRes = new int[] {
            R.id.wgCpu01, R.id.wgCpu02, R.id.wgCpu03, R.id.wgCpu04, R.id.wgCpu05, R.id.wgCpu06,
            R.id.wgCpu07, R.id.wgCpu08, R.id.wgCpu09, R.id.wgCpu10
    };

    private static final int[] wgMemoryRes = new int[] {
            R.id.wgMemory01, R.id.wgMemory02, R.id.wgMemory03, R.id.wgMemory04, R.id.wgMemory05,
            R.id.wgMemory06, R.id.wgMemory07, R.id.wgMemory08, R.id.wgMemory09, R.id.wgMemory10
    };

    private static final int[] wgStorageRes = new int[] {
            R.id.wgStorage01, R.id.wgStorage02, R.id.wgStorage03, R.id.wgStorage04,
            R.id.wgStorage05, R.id.wgStorage06, R.id.wgStorage07, R.id.wgStorage08,
            R.id.wgStorage09, R.id.wgStorage10
    };

    private static final int[] wgSdcardRes = new int[] {
            R.id.wgSdcard01, R.id.wgSdcard02, R.id.wgSdcard03, R.id.wgSdcard04, R.id.wgSdcard05,
            R.id.wgSdcard06, R.id.wgSdcard07, R.id.wgSdcard08, R.id.wgSdcard09, R.id.wgSdcard10
    };

    public static RemoteViews buildUpdate(Context context) {
        RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.widget);
        // NEXT
        Intent intent = new Intent(context, MyBroadcastReceiver.class);

        intent.setAction("btnNext");

        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

        rv.setOnClickPendingIntent(R.id.btnNext, pendingIntent);

        // PREV
        intent = new Intent(context, MyBroadcastReceiver.class);

        intent.setAction("btnPrev");

        pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

        rv.setOnClickPendingIntent(R.id.btnPrev, pendingIntent);

        // 打开电池页面
        intent = new Intent(context, MyTabActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.setAction("battery");
        pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

        rv.setOnClickPendingIntent(R.id.wgBattTemp, pendingIntent);

        // 一键省电
        intent = new Intent(context, MyBroadcastReceiver.class);
        intent.setAction("keyPower");
        pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
//        rv.setOnClickPendingIntent(R.id.wgBtryChickImage, pendingIntent);
        rv.setOnClickPendingIntent(R.id.wgBtryBad_1, pendingIntent);
        rv.setOnClickPendingIntent(R.id.wgBtryBad_2, pendingIntent);
        rv.setOnClickPendingIntent(R.id.wgBtryBad_3, pendingIntent);

        // 打开系统管理页面
        intent = new Intent(context, MyTabActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.setAction("system");
        pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

        rv.setOnClickPendingIntent(R.id.wgStorage, pendingIntent);

        // 一键释放内存

        intent = new Intent(context, MyBroadcastReceiver.class);
        intent.setAction("freeMemory");
        pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

        // rv.setOnClickPendingIntent(R.id.wgStrgChickImage, pendingIntent);
        rv.setOnClickPendingIntent(R.id.wgStrgBad_1, pendingIntent);
        rv.setOnClickPendingIntent(R.id.wgStrgBad_2, pendingIntent);
        rv.setOnClickPendingIntent(R.id.wgStrgBad_3, pendingIntent);


        return rv;
    }

    public static void showNext(Context context, AppWidgetManager appWidgetManager) {

        // Toast.makeText(context, "NEXT", Toast.LENGTH_LONG).show();
        RemoteViews rv = buildUpdate(context);
        rv.setViewVisibility(R.id.wgBtryBackground, View.GONE);
        rv.setViewVisibility(R.id.wgStrgBackground, View.VISIBLE);
        bulidSystemStats(context, rv);

        ComponentName thisWidget = new ComponentName(context, WidgetProvider.class);
        appWidgetManager.updateAppWidget(thisWidget, rv);
        setSystemWidgetShow(context,true);
    }

    public static void showPrev(Context context, AppWidgetManager appWidgetManager) {

        // Toast.makeText(context, "PREV", Toast.LENGTH_LONG).show();

        RemoteViews rv = buildUpdate(context);
        rv.setViewVisibility(R.id.wgBtryBackground, View.VISIBLE);
        rv.setViewVisibility(R.id.wgStrgBackground, View.GONE);

        ComponentName thisWidget = new ComponentName(context, WidgetProvider.class);

        appWidgetManager.updateAppWidget(thisWidget, rv);
        setSystemWidgetShow(context,false);
    }

    /**
     * 获取当前系统状态更新传入的RemoteViews
     * 
     * @param context
     * @param rv
     */
    private static void bulidSystemStats(Context context, RemoteViews rv) {
//        Log.i("tag1", "bulidSystemStats ");
        float memoryUsage = Float.parseFloat(Util.getMemoryInfo(context)[2]);
        float sdcardUsage = Float.parseFloat(Util.getSdCardInfo(context)[2]);
        float storageUsage = Float.parseFloat(Util.getStorageInfo(context)[2]);
        float cpuUsage = Util.getCpuUsage();
        setStatusBar(cpuUsage, rv, wgCpuRes);
        setStatusBar(memoryUsage, rv, wgMemoryRes);
        setStatusBar(sdcardUsage, rv, wgSdcardRes);
        setStatusBar(storageUsage, rv, wgStorageRes);
        // 计算分数
        int score = Util.calculateScore(memoryUsage, storageUsage, sdcardUsage);

        if (score < Constants.SCORE_RED) {
            Util.setRemoteText(R.id.txtStrgDialog, context.getResources().getColor(R.color.red),
                    context.getResources().getString(R.string.widget_system_tips_bad), rv);
            Message msg = new Message();
            msg.arg1 = 0;
            msg.obj = context;
            // 播放动画
            sysChickAnimHandler.sendMessage(msg);

        } else {
            rv.setViewVisibility(R.id.txtStrgDialog, View.GONE);
            for (int id : chickAnimIds) {
                rv.setViewVisibility(id, View.GONE);
            }
            rv.setViewVisibility(R.id.wgStrgChickImage, View.VISIBLE);
        }
    }

    /**
     * 更新系统状态条，可供外部调用
     * 
     * @param context
     */
    public static void updateSystemStats(Context context, boolean isClean) {
//        Log.i("tag1", "bulidSystemStats isSysOrBatteryDisplay "+isSystemWidgetShow(context));
        if(!isSystemWidgetShow(context))
            return;
        AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
        RemoteViews rv = buildUpdate(context);
        bulidSystemStats(context, rv);

        ComponentName thisWidget = new ComponentName(context, WidgetProvider.class);

        if (isClean) {
            rv.setViewVisibility(R.id.txtStrgDialog, View.VISIBLE);
            rv.setTextViewText(R.id.txtStrgDialog,
                    context.getString(R.string.widget_system_tips_cleaning));
            rv.setTextColor(R.id.txtStrgDialog, context.getResources().getColor(R.color.green));
            appWidgetManager.updateAppWidget(thisWidget, rv);
            autoChangeTip(context, R.id.txtStrgDialog,
                    context.getString(R.string.widget_system_tips_ok), new Callback() {

                        @Override
                        public boolean handleMessage(Message msg) {
                            // 把小鸡切换为普通状态
                            Context context = (Context) msg.obj;
                            WidgetUtils.updateSystemStats(context, false);
                            return false;
                        }
                    });
        }

        appWidgetManager.updateAppWidget(thisWidget, rv);

    }

    /**
     * 2秒后自动更新提示。
     * 
     * @param context
     */
    private static void autoChangeTip(final Context context, final int viewId,
            final String content, final Callback callback) {
        final Timer time = new Timer();
        final TimerTask taskDisplay = new TimerTask() {

            @Override
            public void run() {
                RemoteViews rv = WidgetUtils.buildUpdate(context);
                rv.setViewVisibility(R.id.txtBtryDialog, View.INVISIBLE);
                Util.updateWidget(context, rv);
            }

        };
        TimerTask task = new TimerTask() {

            @Override
            public void run() {
                RemoteViews rv = WidgetUtils.buildUpdate(context);
                rv.setViewVisibility(viewId, View.VISIBLE);
                rv.setTextViewText(viewId, content);
                rv.setTextColor(viewId, context.getResources().getColor(R.color.green));
                Util.updateWidget(context, rv);
                if (callback != null) {
                    Message msg = new Message();
                    msg.obj = context;
                    callback.handleMessage(msg);
                }
                time.schedule(taskDisplay, 1000 * 3);
            }

        };
        time.schedule(task, 1000 * 3);
    }

    /**
     * 处理系统界面小鸡动画
     */
    private static Handler sysChickAnimHandler = new Handler() {

        // 循环播放动画
        @Override
        public void handleMessage(Message msg) {
            int index = msg.arg1;
            if (index < chickAnimIds.length) {
                Context context = (Context) msg.obj;
                RemoteViews rv = buildUpdate(context);
                ComponentName thisWidget = new ComponentName(context, WidgetProvider.class);
                AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
                rv.setViewVisibility(R.id.wgStrgChickImage, View.GONE);

                for (int id : chickAnimIds) {
                    if (chickAnimIds[index] != id) {
                        rv.setViewVisibility(id, View.GONE);
                    }
                }
                rv.setViewVisibility(chickAnimIds[index], View.VISIBLE);
                appWidgetManager.updateAppWidget(thisWidget, rv);
                index++;
                Message m = new Message();
                m.obj = msg.obj;
                m.arg1 = index;
                sysChickAnimHandler.sendMessageDelayed(m, 500);
            }

        }

    };

    /**
     * 根据使用率usage更新状态条
     * 
     * @param usage
     * @param rv
     * @param resIds
     */
    private static void setStatusBar(float usage, RemoteViews rv, int[] resIds) {
        int rate = (int) (usage * 10);
        for (int i = 0; i < 10; i++) {
            if (i < 10 - rate)
                rv.setViewVisibility(resIds[i], View.INVISIBLE);
            else
                rv.setViewVisibility(resIds[i], View.VISIBLE);
        }
    }

    /**
     * 小鸡动画图片
     */
    private static final int[] chickAnimIds = new int[] {
            R.id.wgStrgBad_1, R.id.wgStrgBad_2, R.id.wgStrgBad_3, R.id.wgStrgBad_1,
            R.id.wgStrgBad_2, R.id.wgStrgBad_3
    };
    
    public static boolean isSystemWidgetShow(Context context)
    {
        SharedPreferences share = context.getSharedPreferences(Constants.WIZARD_SYSTEM_WIDGET_SHOW,
                Context.MODE_PRIVATE);
        return share.getBoolean(Constants.WIZARD_SYSTEM_WIDGET_SHOW, false);
    }
    
    public static void setSystemWidgetShow(Context context,boolean show)
    {
        SharedPreferences share = context.getSharedPreferences(Constants.WIZARD_SYSTEM_WIDGET_SHOW,
                Context.MODE_PRIVATE);
        Editor edit = share.edit();
        edit.putBoolean(Constants.WIZARD_SYSTEM_WIDGET_SHOW, show);
        edit.commit();       
    }

}
